package niu.toy.spring.mvc.impl.returnValue;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.json.JSONUtil;

import niu.toy.spring.ioc.annotation.Nullable;
import niu.toy.spring.mvc.HandlerMethodParameter;
import niu.toy.spring.mvc.HandlerReturnValue;
import niu.toy.spring.mvc.ModelAndViewContainer;
import niu.toy.spring.mvc.NativeWebRequest;
import niu.toy.spring.mvc.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 返回json格式的数据
 * @author niu
 */
public class ResponseBodyReturnValueHandler implements HandlerReturnValue {

    @Override
    public boolean supportsReturnType(HandlerMethodParameter returnType) {
        return returnType.hasMethodAnnotation(ResponseBody.class);
    }






    @Override
    public void handleReturnValue(@Nullable Object returnValue, HandlerMethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
            throws IOException {
        HttpServletRequest servletRequest = (HttpServletRequest)webRequest.getNativeRequest();
        mavContainer.setRequestHandled(true);
        HttpServletResponse res=(HttpServletResponse)webRequest.getNativeResponse();
        res.setContentType("application/json");
        if(returnValue==null){
            res.getWriter().write("{}");
        }else{
            Class returnCls=returnValue.getClass();
            if (returnValue instanceof CharSequence|| ClassUtil.isSimpleValueType(returnCls)) {
                res.setContentType("html/text");
                res.getWriter().write(returnValue.toString());
            }else{
                res.getWriter().write(JSONUtil.toJsonStr(returnValue));
            }
        }
        res.getWriter().flush();
    }

}
